﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using Alone;
using AloneLibrary.Services.Camera;

namespace NetworkStateManagement.Classes
{
    class PlayerHandler : DrawableGameComponent
    {
        Player player;
        Vector3 position = new Vector3(0, 0, 0);
        Vector3 direction = Vector3.Zero;
        float scale = 1;
        Vector3 velocity = Vector3.Zero;
        Matrix world;

        ThirdPersonCamera camera;
        
        public PlayerHandler(Game game) : base(game)
        {
            player = new Player(game.Content.Load<Model>(@"Models\dude"),position,direction,scale,velocity);
        }

        public Player Player 
        {
            get { return this.player; }
        }
        
        public override void Initialize()
        {
            camera = (ThirdPersonCamera)Game.Services.GetService(typeof(ThirdPersonCamera));
            base.Initialize();
        }

        protected override void LoadContent()
        {
            world = Matrix.Identity;
            base.LoadContent();
        }

        public override void Draw(GameTime gameTime)
        {
            Matrix[] transforms = new Matrix[player.Model.Bones.Count];
            
            player.Model.CopyAbsoluteBoneTransformsTo(transforms);

            world = Matrix.CreateScale(player.Scale)
                * Matrix.CreateRotationY(player.Direction.Y)
                * Matrix.CreateTranslation(player.Position);

            camera.UpdateCameraThirdPerson(player.Direction.Y, player.Position);

            foreach (ModelMesh modmesh in player.Model.Meshes)
            {
                foreach (BasicEffect effect in modmesh.Effects)
                {
                    effect.EnableDefaultLighting();
                    effect.PreferPerPixelLighting = true;
                    effect.World = transforms[modmesh.ParentBone.Index] * world;
                    effect.Projection = camera.Projection;
                    effect.View = camera.View;
                }

                modmesh.Draw();
            }
            base.Draw(gameTime);
        }
    }
}
